<template>
  <div class="view grid-nosku" style="margin-left: 180px">
    <div
      class="product"
      v-for="product in productList"
      :key="product.productId"
    >
      <div class="product-iWrap">
        <div class="productImg-wrap">
          <img
            :src="product.productImg.length === 0 ? null : product.productImg"
            alt="Product Image"
            @click="toBookDetail(product)"
          />
        </div>
        <p class="productPrice">
          <em><b>¥</b>{{ product.price.toFixed(2) }}</em>
        </p>
        <p class="productTitle">
          <a v-html="product.productName"></a>
        </p>
        <div class="productShop">
          <span>店铺：新华书店</span>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-size="pageSize"
      :current-page="pageNow"
      @current-change="getProduct"
      @size-change="handleSizeChange"
      :page-sizes="[5, 10, 15, 20]"
    ></el-pagination>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      src: "",
      total: 0, // 总数据量
      pageSize: 15, // 每页显示条数
      pageNow: 1, // 当前页码
      productList: [], // 当前页的数据
    };
  },
  methods: {
    // 获取产品数据
    getProduct(page = 1) {
      this.pageNow = page; // 更新当前页码
      axios
        .get("/getProduct", {
          params: {
            pageNow: this.pageNow,
            pageSize: this.pageSize,
          },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          },
        })
        .then((res) => {
          // 获取到数据后更新表格内容
          const data = res.data.data.data;
          if (data.productCount === 0) {
            alert("不好意思没有该书的信息，请联系管理员KK");
            return;
          }
          this.productList = data.products || [];
          this.total = data.productCount || 0; // 更新总数据量
        })
        .catch((error) => {
          console.error("获取产品失败：", error);
        });
    },
    //
    toBookDetail(product) {
      this.$router.push({
        path: "/product-detail",
        query: { productId: product.productId },
      });
      location.reload();
    },

    // 每页显示条数改变时
    handleSizeChange(val) {
      this.pageSize = val; // 更新每页条数
      this.getProduct(1); // 从第一页开始获取数据
    },
  },
  created() {
    console.log("初始化......");
    this.getProduct(); // 页面加载时默认获取第一页的数据
  },
};
</script>

<style scoped src="../../assets/css/style.css"></style>
